﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class CombatView : IUIView
{
    public Text oldCoin;
    public Text newCoin;
    public int hp;
    public Transform hpRoot;
    CharacterInfo characterInfo;
    List<GameObject> hps = new List<GameObject>();
    public override void Initinalize()
    {
    
    }

    private void CoinChange(int arg1, int arg2)
    {
        string s = arg2.ToString();
        oldCoin.text = s;
        int change = arg2 - arg1;
        string nc = change.ToString();
        if (change>0)
        {
            newCoin.text = "+" + nc;
        }
        else
        {
            newCoin.text = "-" + nc;
        }
        newCoin.color = new Color(1, 1, 1, 0);
        newCoin.DOFade(1,0.5f).SetLoops(2,LoopType.Yoyo);
    }

    private void HpChange(int old, int newHp)
    {
        for (int i = 0; i < hps.Count; i++)
        {
            if (i<newHp)
            {
                hps[i].gameObject.SetActive(true);
            }
            else
            {
                hps[i].gameObject.SetActive(false);
            }
            
        }

    }

    public void BindCharacter( CharacterInfo characterInfo)
    {
        this.characterInfo = characterInfo;
        InitCombatUI();
    }
    public void ResetView()
    {
        characterInfo.onHpChange = null;
        characterInfo.onCoinChange = null;
        characterInfo = null;
        hps.Clear();

    }
    void InitCombatUI()
    {
        oldCoin.text = characterInfo.hp.ToString();
        hp = characterInfo.hp;
        int count = 0;
        count = characterInfo.maxHp - hpRoot.childCount;

        for (int i = 0; i < hpRoot.childCount; i++)
        {
            hps.Add(hpRoot.GetChild(i).gameObject);
        }

        for (int i = 0; i < count; i++)
        {
            GameObject obj= Instantiate(Resources.Load<GameObject>("Prefabs/UI/hpImage"),hpRoot);
            hps.Add(obj);
        }
        for (int i = 0; i < hps.Count; i++)
        {
            if (i<hp)
            {
                hps[i].gameObject.SetActive(true);
            }
            else
            {
                hps[i].gameObject.SetActive(false);
            }
        }
        characterInfo.onHpChange = HpChange;
        characterInfo.onCoinChange = CoinChange;
    }
    
    public override void Show()
    {
        base.Show();
    }
    public override void Hide()
    {
        base.Hide();
    }
}
